package com.csw.shuanfa.CodeImprove.CompleteFutureLinkedBlockingQueue;

import com.csw.shuanfa.utils.ThreadPoolUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * @author chengshuaiwei
 */
public class ThreadPoolTest {

    private static final int num = 1000;

    public static void main(String[] args) throws Exception {

        ExecutorService threadPool = ThreadPoolUtil.getExecutorServiceCPU(1);


        List<CompletableFuture> completableFutureList = new ArrayList<>();
        //1、
        try {
            for (int i = 0; i < Integer.MAX_VALUE; i++) {
                final int taskId = i;
                threadPool.execute(() -> {
                    System.out.println("执行任务2 " + taskId);
                });
            }
            long t1 = System.currentTimeMillis();
            AtomicInteger a = new AtomicInteger();
            CountDownLatch countDownLatch = new CountDownLatch(num);

            for (int i = 0; i < num; i++) {
                threadPool.execute(() -> {
                    //每个步骤都用调用线程池里面的线程来做
                    try {
                        Thread.sleep(10);
                        //int aa=1/0;
                    } catch (InterruptedException e) {
                        //2、错误时打印信息
                        e.printStackTrace();
                    } finally {
                        a.getAndIncrement();
                        countDownLatch.countDown();
                    }
                });
            }

            //2、保证上面每一个异步执行完，设置超时获取时间，跑批不需要
            boolean await = countDownLatch.await(3, TimeUnit.MILLISECONDS);


            CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
            }, threadPool);
            completableFutureList.add(future1);

            //批量阻塞完成
            // CompletableFuture.allOf(futureList.toArray(futureList.toArray(new CompletableFuture[0]))).get(1, TimeUnit.SECONDS);
            //CompletableFuture.allOf(future1, future2, future3, future4, future5, future6, future7).get(1, TimeUnit.SECONDS);
            long t2 = System.currentTimeMillis();
            System.out.println("总共耗时：" + (t2 - t1));
        } catch (Exception e) {
            //3、
            System.out.println(ThreadPoolUtil.getThreadPoolNameMethod());
            threadPool.shutdownNow();
            throw new RuntimeException(e);
        } finally {
            threadPool.shutdown();
        }
    }


}
